define(['app'], function(app) {
    app.controller('CopyMockController', function($scope, $http, xContext, $uibModalInstance, xDialog, xUtil, toastr) {
        var self = this;
        self.type = '';
        self.source = '';
        self.target = '';
        self.extname = '';
        self.movable = false;
        self.nestpath = false;
        self.ignored = { folder: true, file: true };

        self.init = function() {
            self.type = xContext.type;
            var nodeName = xContext.node.name;
            if (self.type == 'file') {
                var dotIndex = nodeName.indexOf('.');
                if (dotIndex != -1) {
                    self.extname = nodeName.substring(dotIndex);
                    nodeName = nodeName.substring(0, dotIndex);
                }
            }
            self.source = xUtil.path.join([xContext.node.parent, nodeName]);

            if (self.type == 'folder') {
                var rpath = new RegExp('^' + self.source + '/\{?[0-9A-Za-z_-]+\}?', 'i');
                $scope.$watch('dvm.target', function(newValue) {
                    self.nestpath = (newValue && rpath.test(newValue));
                });
            }
        }

        self.copy = function(valid) {
            if (valid && self.target != self.source && !self.nestpath) {
                $http.post('/mock/data/copy', {
                    type: self.type,
                    module: xContext.module,
                    source: self.source + (self.type == 'file' ? self.extname : ''),
                    target: self.target + (self.type == 'file' ? self.extname : ''),
                    ignored: self.ignored,
                    movable: self.movable
                }).then(function(response) {
                    if (response.data == 'required') {
                        xDialog.alert('提示信息', '数据模块【' + xContext.module + '】不存在！');
                    } else if (response.status == 200) {
                        if (self.type == 'file') {
                            toastr.success('文件已复制！');
                        } else {
                            toastr.success('文件夹已复制！');
                        }
                        $uibModalInstance.close({
                            path: self.target + (self.type == 'file' ? self.extname : '/')
                        });
                    }
                });
            }
        }

        self.cancel = function() {
            $uibModalInstance.dismiss();
        }
    });
});
